/*
	This file is part of the JKTest
    Copyright (C) 2008 Royce Y. Feng <ryfeng@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License version 3
    as published by the Free Software Foundation. You may not use, modify
    or distribute this program under any other version of the
    GNU Affero General Public License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package JKPanels;

import JKDateAndTime.DateAndTimeClass;
import java.awt.Dimension;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
import java.net.InetAddress;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Random;

import java.util.TimeZone;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;

import jktest.JKMainPanel;
import jktest.JKMainGui;
import jktest.JMultilineLabel;
import jktest.JKButton;

/**
 * 
 * Panel Class containing all elements of the Ethernet Test
 * 
 * @author Royce Feng
 */

public class EthernetPanel extends JKMainPanel {

    private PassFailPanel passFail;
    private Random gen = new Random();
    public static final String TIME_SERVERS = "nist1-ny.ustiming.org,nist1-nj.ustiming.org,nist1-pa.ustiming.org,time-a.nist.gov,time-b.nist.gov,"
            + "nist1.aol-va.symmetricom.com,nist1.columbiacountyga.gov,nist1-atl.ustiming.org,nist1-chi.ustiming.org,nist1.expertsmi.com,"
            + "nist.netservicesgroup.com,nisttime.carsoncity.k12.mi.us,wwv.nist.gov,time-a.timefreq.bldrdoc.gov,time-b.timefreq.bldrdoc.gov,"
            + "time-c.timefreq.bldrdoc.gov,time.nist.gov,utcnist.colorado.edu,utcnist2.colorado.edu,ntp-nist.ldsbc.edu,nist1-lv.ustiming.org,"
            + "time-nw.nist.gov,nist1.aol-ca.symmetricom.com,nist1.symmetricom.com,nist1-sj.ustiming.org,nist1-la.ustiming.org";
    public static final String ATOMICTIME_SERVER="http://64.90.182.55";
    
    /**
     * 
     * Main Constructor for EthernetPanel. Creates a multiline label with instructions
     * as well as the three main buttons: Start test, Pass, Fail.
     * 
     * @param _parent The Parent Class (for communication)
     */
    public EthernetPanel ( JKMainGui _parent ) {
        super(_parent);
        JMultilineLabel instructions = new JMultilineLabel();
        instructions.setMaxWidth(500);
        instructions.setText("After you click the button, and internet explorer window will popup. If it manages" +
                "to load a page just fine, the test is passed.");
        this.add(instructions);
        JKButton button = new JKButton(this,"Automatic Test");
        button.setPreferredSize(new Dimension(200,25));
        this.add( button );
        JKButton button2 = new JKButton(this,"Manual Test");
        button2.setPreferredSize(new Dimension(200,25));
        this.add(button2);
        passFail = new PassFailPanel(this);
        passFail.setPreferredSize(new Dimension(500,25));
        this.add(passFail);
    }
    
    /**
     * 
     * Returns the name of the panel
     * 
     * @return The name of the panel
     */
    @Override
    public String getName() {
        return "Ethernet";
    }
    public GregorianCalendar getAtomicTime() throws IOException{
        String[] servers = TIME_SERVERS.split(",");
        String TIME_SERVER = servers[gen.nextInt(servers.length)];
        NTPUDPClient timeClient = new NTPUDPClient();
        InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
        TimeInfo timeInfo = timeClient.getTime(inetAddress);
        Date time = timeInfo.getMessage().getTransmitTimeStamp().getDate();
        System.out.println("Time from " + TIME_SERVER + ": " + time.toString());
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(time);
        return cal;
    }
    /**
     * 
     * Handles button clicks. Pass/fail gets sent to parent while the test is run
     * when the test button is clicked.
     * 
     * @param source Button source (usually the button text)
     */
    public void ButtonClicked( String source ) {
        if ( source.equals("Pass") ) {
            getThisParent().valChanged(this.getName(), true);
            getThisParent().incPanel();
        } else if ( source.equals("Fail") ) {
            getThisParent().valChanged(this.getName(), false);
            getThisParent().incPanel();
        } else if ( source.equals("Manual Test") ) {
            // Opens www.google.com in default browser
            String osName = System.getProperty("os.name");
            if (osName.toUpperCase().startsWith(("WINDOWS"))) {
                try {
                    String cmdLine = "cmd.exe /c start www.google.com";
                    Runtime.getRuntime().exec(cmdLine);
                } catch ( IOException e ) {
                    JOptionPane.showMessageDialog(this, "URL Stream cannot be accessed", "Program Error", JOptionPane.ERROR_MESSAGE);
                    getThisParent().valChanged(this.getName(), false);
                }
            } else {
                JOptionPane.showMessageDialog(this,"Current Operating System is not windows","Unrecognized Operating System", JOptionPane.ERROR_MESSAGE);
            }
        } else if ( source.equals("Automatic Test") ) {
            /*
            if ( getThisParent().getMessageState() )
                JOptionPane.showMessageDialog(this, "Ethernet test is an automated procedure that accesses " +
                    "google. If you wish to manually test, please open up a webpage via a web browser",
                    "Automated Procedure", JOptionPane.INFORMATION_MESSAGE);
            */
            try {
                URL url = new URL("http://www.google.com");
                InputStream in = url.openStream();
                BufferedReader inReader = new BufferedReader ( new InputStreamReader(in) );
                //DataInputStream inReader = new DataInputStream(new BufferedInputStream(in));
                String line;
                while ( (line = inReader.readLine()) != null ) {
                    if ( line.contains("HTTP 500") || line.contains("HTTP500") ) {
                        getThisParent().valChanged(this.getName(), false);
                    }
                }
                inReader.close();
                in.close();
            } catch ( MalformedURLException e ) {
                JOptionPane.showMessageDialog(this, "URL cannot be accessed", "Program Error", JOptionPane.ERROR_MESSAGE);
                getThisParent().valChanged(this.getName(), false);
            } catch ( IOException e ) {
                JOptionPane.showMessageDialog(this, "URL Stream cannot be accessed", "Program Error", JOptionPane.ERROR_MESSAGE);
                getThisParent().valChanged(this.getName(), false);
            }
            try {
                GregorianCalendar cal = getAtomicTime();
                Calendar cal2 = Calendar.getInstance();
                if (Math.abs(cal.getTimeInMillis()-cal2.getTimeInMillis()) > 1000*60) {
                    int confirmation = JOptionPane.showConfirmDialog(null,"Time found was off by more than a minute. Do you want to reset the time?",
                    "Confirmation",JOptionPane.YES_NO_OPTION);
                    if ( confirmation == JOptionPane.YES_OPTION ) {
                        DateAndTimeClass.setDateAndTime(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), 
                            cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));
                    }
                }
            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "Time could not be gotten from web service", "Program Error", JOptionPane.ERROR_MESSAGE);
            }
            getThisParent().valChanged(this.getName(), true);
        }
    }    
    
}
